package com.dk.controller;

import com.alibaba.fastjson.JSONObject;
import com.dk.dto.LogServerDTO;
import com.dk.dto.UserDTO;
import com.dk.em.Result;
import com.dk.em.ResultEnum;
import com.dk.util.JWTUtil;
import com.dk.vo.UserVO;
import io.swagger.annotations.ApiOperation;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@RestController
@RequestMapping("login")
@RefreshScope       //开启热更新
public class LoginController {

    @Autowired
    private JWTUtil jwtUtil;//单点登录

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @ApiOperation("登录接口")
    @PostMapping    //请求头注解:注意:不支持中文   建议:可以用@RequestParme   或者什么注解都不加
    public Result login(@RequestParam String username,@RequestParam String password){
        //@RequestHeader String stuts
//        System.out.println("-------->>>"+stuts);//注意由于网关配置的参数  是在请求头获取的所以要加个注解
        //1.获取对象
        Subject subject = SecurityUtils.getSubject();
        //2.封装数据
        UsernamePasswordToken usernamePasswordToken=new UsernamePasswordToken(username,password);
        try {
            //3.进入认证方法
            subject.login(usernamePasswordToken);

            //#单点登录#  获取当前用户
            UserDTO user = (UserDTO) SecurityUtils.getSubject().getPrincipal();
            //脱敏处理
            UserVO userVO=new UserVO();
            BeanUtils.copyProperties(user,userVO);
            //生成token
            String jwt = jwtUtil.createJwt(userVO.getUId().toString(), JSONObject.toJSONString(userVO), "roles");

            //#发送MQ存日志消息#   用户登录时间    用户登录时使用的名称   登录时返回的信息  token   客户端ip
            LogServerDTO dto=new LogServerDTO();
            dto.setLogintime(new Date());
            dto.setToken(jwt);
            dto.setUsername(user.getUName());
            rocketMQTemplate.convertAndSend("loginTopic",dto);
            return Result.ZHRESPONSE(ResultEnum.LOGIN_SUCCESS_DATA).setData(jwt);
        }catch (UnknownAccountException unknownAccountException){
            return Result.ZHRESPONSE(ResultEnum.USERNAME_PASSWORD_ERROR_DATA);
        }catch (IncorrectCredentialsException incorrectCredentialsException){
            return Result.ZHRESPONSE(ResultEnum.USERNAME_PASSWORD_ERROR_DATA);
        }
    }
}
